<template>
  <div class="editable-table-container">
    <div class="operation-bar" v-if="selectedRowKeys.length > 0">
      <span class="selected-count">已选择 {{ selectedRowKeys.length }} 项</span>
      <t-space>
        <t-button theme="warning" @click="handleBatchDelete">批量删除</t-button>
        <t-button theme="primary" @click="handleBatchDispatch">批量调度</t-button>
      </t-space>
    </div>

    <t-table 
      :data="dataSource" 
      :columns="columns" 
      row-key="key"
      bordered
      :pagination="false"
      :selected-row-keys="selectedRowKeys"
      @select-change="onSelectChange"
    >
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      
      <template #amount="{ row }">
        <div class="editable-cell">
          <t-input-number
            v-model="row.amount"
            :min="0"
            class="editable-input"
            @change="(val) => handleDataChange(row.key, val)"
          />
        </div>
      </template>
    </t-table>

    <div class="table-footer">
      <t-button 
        theme="primary" 
        :loading="saving"
        @click="handleSave"
      >
        保存
      </t-button>
    </div>

    <DispatchModal 
      :data="dispatchData" 
      :visible="dispatchModalVisible" 
      @update:visible="dispatchModalVisible = $event"
      @success="handleDispatchSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import DispatchModal from '../components/DispatchModal.vue';

interface DataItem {
  key: string;
  region: string;
  amount: number;
  status: number;
}

// 定义表格列
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple',
    width: '8%',
    align: 'center',
    disabled: ({ row }) => row.status !== 2,
  },
  {
    title: '序号',
    colKey: 'index',
    width: '12%',
    align: 'center',
    cell: 'index',
  },
  {
    title: '行政区划',
    colKey: 'region',
    width: '40%',
  },
  {
    title: '数量',
    colKey: 'amount',
    width: '40%',
    cell: 'amount',
  },
];

// 模拟数据
const dataSource = ref<DataItem[]>([
  {
    key: '1',
    region: '浙江省',
    amount: 120,
    status: 2,
  },
  {
    key: '2',
    region: '江苏省',
    amount: 150,
    status: 1,
  },
  {
    key: '3',
    region: '上海市',
    amount: 80,
    status: 2,
  },
  {
    key: '4',
    region: '广东省',
    amount: 200,
    status: 1,
  },
]);

const dispatchData = ref<DataItem[]>([]);
// 选中的行
const selectedRowKeys = ref<string[]>([]);

// 记录修改过的数据
const modifiedData = reactive(new Map<string, number>());
const saving = ref(false);
const dispatchModalVisible = ref(false);


// 处理数据变化
const handleDataChange = (key: string, value: number) => {
  modifiedData.set(key, value);
};

// 刷新表格数据
const refreshTableData = (modifiedRecords: DataItem[]) => {
  modifiedRecords.forEach(record => {
    const index = dataSource.value.findIndex(item => item.key === record.key);
    if (index !== -1) {
      dataSource.value[index] = { ...record };
    }
  });
};

// 处理保存操作
const handleSave = async () => {
  if (modifiedData.size === 0) {
    alert('没有数据被修改');
    return;
  }

  saving.value = true;
  try {
    // 获取修改过的数据
    const modifiedRecords = dataSource.value.filter(item => 
      modifiedData.has(item.key)
    ).map(item => ({
      ...item,
      amount: modifiedData.get(item.key) || item.amount
    }));

    // 这里可以发送API请求保存数据
    await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟API请求
    console.log('修改的数据：', modifiedRecords);

    // 更新表格数据
    refreshTableData(modifiedRecords);
    
    // 清空修改记录
    modifiedData.clear();
    alert('保存成功！');
  } catch (error) {
    alert('保存失败，请重试');
  } finally {
    saving.value = false;
  }
};

// 处理多选变化
const onSelectChange = (value: string[], selectedRows: DataItem[]) => {
  selectedRowKeys.value = value;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    MessagePlugin.warning('请选择要删除的项');
    return;
  }

  if (confirm('确定要删除选中的项吗？')) {
    dataSource.value = dataSource.value.filter(
      item => !selectedRowKeys.value.includes(item.key)
    );
    selectedRowKeys.value = [];
    MessagePlugin.success('删除成功');
  }
};

// 批量调度
const handleBatchDispatch = () => {
  if (selectedRowKeys.value.length === 0) {
    MessagePlugin.warning('请选择要调度的项');
    return;
  }

  const selectedData = dataSource.value.filter(
    item => selectedRowKeys.value.includes(item.key)
  );
  dispatchData.value = selectedData;
  dispatchModalVisible.value = true;
};

// 处理调度成功
const handleDispatchSuccess = () => {
  selectedRowKeys.value = [];
  MessagePlugin.success('调度成功');
};

const getLeft = async () => {
  try {
    // 并行请求两个接口
    const [enterData, insureData] = await Promise.all([
      getData({ period: industry.value }),
      getInsuranceData({ period: industry.value })
    ]);

    // 创建保险数据的快速查找映射
    const insureMap = new Map(
      insureData?.data?.records.map(item => [item.districtName, item.insureCount]) || []
    );

    // 合并数据
    emergencyList.value = enterData?.data?.records.map(item => ({
      county: item.districtName,
      enterCount: item.enterCount,
      insureCount: insureMap.get(item.districtName) || 0
    })) || [];

    // 计算总计
    totileList.value = [{
      county: '总计',
      enterCount: emergencyList.value.reduce((sum, item) => sum + Number(item.enterCount), 0),
      insureCount: emergencyList.value.reduce((sum, item) => sum + Number(item.insureCount), 0)
    }];
  } catch (error) {
    console.error('数据获取失败:', error);
    // 可以添加错误提示
  }
};


</script>

<style scoped>
.editable-table-container {
  padding: 24px;
}

.operation-bar {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-count {
  color: #666;
}

.editable-cell {
  padding: 5px;
}

.editable-input {
  width: 100%;
}

.table-footer {
  margin-top: 16px;
  text-align: center;
}
</style> 